import {create, deleteById, findOne, list, modify} from '@/services/node-api';
import {PlusOutlined} from '@ant-design/icons';
import {RadialBar} from '@ant-design/plots';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProDescriptions,
  ProDescriptionsItemProps,
  ProTable
} from '@ant-design/pro-components';
import {Button, Drawer, message, Modal, Space} from 'antd';
import React, {useRef, useState} from 'react';
import CreateOrUpdateForm from './components/CreateOrUpdateForm';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.Node) => {
  const hide = message.loading('正在添加');
  try {
    const res = await create({...fields});
    hide();
    if (res) {
      message.success('添加成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.Node) => {
  const hide = message.loading('更新中');
  try {
    const res = await modify(fields);
    hide();

    if (res) {
      message.success('更新成功');
      return true;
    }
    return false;
  } catch (error) {
    hide();
    return false;
  }
};

const commonColumns: ProColumns<API.Node>[] = [
  {
    title: '序号',
    dataIndex: 'id',
    hideInSearch:true,
  },
  {
    title: '机器名字',
    dataIndex: 'name'
  },
  {
    title: '地址端口',
    renderText: (_, record) => `${record.ip}:${record.port}`,
    hideInSearch:true,
  },
  {
    title: '运行状态',
    dataIndex: ['status'],
    valueEnum: {
      'START': {text: '已启动', status: 'Processing'},
      'STOP': {text: '未启动' , status: 'Default'}
    },
    hideInSearch:true,
  },
]

export const descriptionColumns: ProColumns<API.NodeDTO>[] = [
  ...commonColumns,
  {
    title: '下载端口',
    dataIndex: ['parameters','downloadPort']
  },
  {
    title: 'MBean端口',
    dataIndex: ['parameters','mbeanPort']
  },
  {
    title: '启用外部IP',
    dataIndex: ['parameters', 'useExternalIp'],
    renderText: (home: any) => home ? '是' : '否'
  },
  {
    title: 'Zookeeper集群',
    renderText: (_, record) => `${record?.parameters?.zkCluster?.clusterName || '' }[${record?.parameters?.zkCluster?.serverList?.join(";") || ''}]`,
  },
  {
    title: '使用内存',
    render: (_,record)=>{
      const hp = record?.heapMemoryUsage;
      if (!hp || !hp?.committed || !hp?.max || !hp?.used){
        return <></>;
      }
      const used = hp.used / 1000 / 1000;
      const committed = hp.committed / 1000 / 1000;
      const max = hp.max /1000 / 1000;
      const data = [
        { name: '已使用内存', star: used },
        { name: '已申请内存', star: committed },
        { name: '最大可用内存', star: max },
      ];

      const config = {
        data,
        xField: 'name',
        yField: 'star',
        maxAngle: 350,
        radius: 1,
        innerRadius: 0.2,
        tooltip: {
          items: ['star'],
        },
        legend: false,
        axis: {
          y: false,
        },
        markBackground: {
          opacity: 0.25,
        },
        scale: {
          y: {
            domain: [0, max * 1.1], // 设定范围用于背景图的渲染获取最大值
          },
        },
        style: {
          radius: 180,
          // @ts-ignore
          fill: ({ star }) => {
            // @ts-ignore
            if (star === max) {
              return '#6349ec';
              // @ts-ignore
            } else if (star === committed) {
              return '#ff9300';
            }
            return '#ff93a7';
          },
        },
      };
      return <RadialBar {...config} />;
    },
  },

  {
    title: '线程使用状况',
    dataIndex: ['threadPoolSize'],
  },
  {
    title: 'node版本信息',
    dataIndex: ['versionInfo'],
  },
  {
    title: '操作系统信息',
    dataIndex: ['systemInfo'],
  },
  {
    title: '操作系统信息',
    dataIndex: ['description'],
  },
];

const Node: React.FC = () => {

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [createOrUpdateModalOpen, handleCreateOrUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [isCreate, handleIsCreate] = useState<boolean>(true);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Node>();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.Node) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
      const res = await deleteById(selectedRows.id);
      hide();
      if (res) {
        message.success('删除成功');
        actionRef.current?.reload();
        return true;
      }
      return false;
    } catch (error) {
      hide();
      return false;
    }
  };


  const columns: ProColumns<API.SeniorNode>[] = [
    ...commonColumns,
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (<>
        <Space>
          <a
            key="detail"
            onClick={() => {
              setCurrentRow(record);
              setShowDetail(true);
            }}
          >
            查看
          </a>
          {record?.status === 'STOP' && (
          <a
            key="edit"
            onClick={() => {
              handleCreateOrUpdateModalOpen(true);
              handleIsCreate(false);
              setCurrentRow(record);
            }}
          >
            编辑
          </a>)
          }

          { !record?.used && (
            <>
              <a
                type='button'
                key="delete"
                onClick={() => {
                  Modal.confirm({title: '确实删除?', onOk: () => handleRemove(record)});
                }}
              >删除
              </a>
            </>
          )}
        </Space></>)

    }
  ];

  return (
    <PageContainer>
      <ProTable<API.AutoKeeperCluster, API.PageParams>
        headerTitle='Node列表'
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleIsCreate(true);
              handleCreateOrUpdateModalOpen(true);
            }}
          >
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={list}
        columns={columns}
      />
      <CreateOrUpdateForm
        onSubmit={async (value) => {
          let success;
          if (currentRow?.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleCreateOrUpdateModalOpen(false);
            setCurrentRow(undefined);
            await actionRef?.current?.reload();
          }
        }}
        title={isCreate ? '新建' : '编辑'}
        onCancel={() => {
          handleCreateOrUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={createOrUpdateModalOpen}
        values={currentRow}
      />

      <Drawer
        width={500}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<API.Node>
            column={1}
            title={currentRow?.name}
            request={async () => findOne(currentRow?.id)}
            params={{
              id: currentRow?.id,
            }}
            columns={descriptionColumns as ProDescriptionsItemProps<API.Node>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default Node;
